<template>
  <div class="config-group">
    <h4>图表组件配置</h4>
    
    <!-- 基础配置 -->
    <div class="config-section">
      <div class="section-title">基础配置</div>
      <!-- 尺寸和背景 -->
      <div class="config-row">
        <div class="config-item">
          <label>宽度：</label>
          <input 
            type="text" 
            v-model="localConfig.width"
            @input="updateConfig"
            placeholder="例如：100%"
          >
        </div>
        <div class="config-item">
          <label>高度：</label>
          <input 
            type="text" 
            v-model="localConfig.height"
            @input="updateConfig"
            placeholder="例如：300px"
          >
        </div>
        <div class="config-item">
          <label>背景颜色：</label>
          <el-color-picker 
            v-model="localConfig.backgroundColor"
            show-alpha
            @change="updateConfig"
            size="small"
          />
      </div>
    </div>

      <!-- 图表类型和数据来源 -->
      <div class="config-row">
        <div class="config-item">
            <label>图表类型：</label>
            <select v-model="chartType" @change="handleChartTypeChange">
              <option value="line">折线图</option>
              <option value="bar">柱状图</option>
            </select>
          </div>
        <div class="config-item">
          <label>数据来源：</label>
              <select v-model="dataSourceType" @change="handleDataSourceChange">
                <option value="static">静态数据</option>
                <option value="api">远程接口</option>
              </select>
        </div>
            </div>
          </div>

    <!-- 数据配置 -->
    <div class="config-section">
      <div class="section-title">数据配置</div>

      <div v-if="dataSourceType === 'api'" class="api-config">
        <!-- API配置部分 -->
        <div class="config-row">
          <div class="config-item">
            <label>接口地址：</label>
            <input 
              type="text"
              v-model="apiConfig.url"
              @input="handleApiConfigChange"
              placeholder="请输入接口地址"
            >
          </div>
          <div class="api-reference" style="margin-top: 10px; color: #409EFF;">
            参考接口: <a href="http://cylyxsz.w1.luyouxia.net/api/chart-data" target="_blank" style="color: #409EFF;">http://cylyxsz.w1.luyouxia.net/api/chart-data</a>
          </div>
        </div>

        <div class="config-row">
          <div class="config-item">
            <label>请求方法：</label>
            <select v-model="apiConfig.method" @change="handleApiConfigChange">
              <option value="GET">GET</option>
              <option value="POST">POST</option>
            </select>
          </div>
          <div class="config-item">
            <label>自动刷新：</label>
            <el-switch
              v-model="apiConfig.autoRefresh"
              @change="handleApiConfigChange"
            />
          </div>
          <div class="config-item" v-if="apiConfig.autoRefresh">
            <label>刷新间隔：</label>
            <input 
              type="number"
              v-model.number="apiConfig.refreshInterval"
              @input="handleApiConfigChange"
              min="1"
              placeholder="单位：秒"
            >
          </div>
        </div>

        <!-- 数据映射配置 -->
        <div class="mapping-config">
          <div class="mapping-example">
            <pre class="example-code">接口返回格式：
{
  "code": 200,
  "data": {
    "categories": ["Mon", "Tue", "Wed"],
    "series": [{
      "name": "销量",
      "data": [120, 200, 150]
    }]
  }
}</pre>
          </div>
          <div class="config-row">
            <div class="config-item">
              <label>分类路径：</label>
              <input 
                type="text"
                v-model="apiConfig.mapping.categories"
                @input="handleApiConfigChange"
                placeholder="例如：data.categories"
              >
            </div>
            <div class="config-item">
              <label>系列路径：</label>
              <input 
                type="text"
                v-model="apiConfig.mapping.series"
                @input="handleApiConfigChange"
                placeholder="例如：data.series"
              >
            </div>
          </div>
        </div>

        <!-- 测试接口按钮 -->
        <div class="api-actions">
          <button class="test-api-btn" @click="testApi">测试接口</button>
        </div>

        <!-- 图表样式配置 -->
        <div class="chart-style-config">
          <!-- 系列配置 -->
          <div class="series-config">
            <div class="series-header">
              <span>数据系列样式</span>
              <button class="add-btn" @click="addSeries">添加系列</button>
            </div>
            
            <div v-for="(series, index) in localConfig.option.series" 
                 :key="index" 
                 class="series-item">
              <div class="series-row">
                <div class="config-item">
                  <label>系列名称：</label>
                  <input 
                    type="text" 
                    v-model="series.name"
                    @input="updateConfig"
                    placeholder="系列名称"
                  >
                </div>
                <div class="config-item">
                  <label>图表类型：</label>
                  <select 
                    v-model="series.type"
                    @change="handleSeriesTypeChange(index)"
                  >
                    <option value="line">折线图</option>
                    <option value="bar">柱状图</option>
                  </select>
                </div>
                <div class="config-item">
                  <label>系列颜色：</label>
                  <el-color-picker 
                    v-model="series.itemStyle.color"
                    show-alpha
                    @change="updateConfig"
                    size="small"
                  />
                </div>
                <button 
                  v-if="localConfig.option.series.length > 1"
                  @click="removeSeries(index)" 
                  class="remove-btn"
                >删除</button>
              </div>

              <!-- 系列数据输入 -->
              <div class="series-data-input">
                <div class="config-item">
                  <label>系列数据：</label>
                  <textarea
                    v-model="seriesDataInputs[index]"
                    @input="handleSeriesDataInput($event, index)"
                    :placeholder="getSeriesPlaceholder()"
                    rows="2"
                  ></textarea>
                </div>
              </div>

              <!-- 折线图特有配置 -->
              <div v-if="series.type === 'line'" class="series-style-row">
                <div class="config-item">
                  <label>线条宽度：</label>
                  <input 
                    type="number" 
                    v-model.number="series.lineStyle.width"
                    @input="updateConfig"
                    min="1"
                    max="10"
                  >
                </div>
                <div class="config-item">
                  <label>是否平滑：</label>
                  <el-switch
                    v-model="series.smooth"
                    @change="updateConfig"
                  />
                </div>
              </div>

              <!-- 柱状图特有配置 -->
              <div v-if="series.type === 'bar'" class="series-style-row">
                <div class="config-item">
                  <label>柱条宽度：</label>
                  <input 
                    type="number" 
                    v-model.number="series.barWidth"
                    @input="updateConfig"
                    min="10"
                    max="50"
                  >
                </div>
                <div class="config-item">
                  <label>柱条间距：</label>
                  <input 
                    type="text" 
                    v-model="series.barGap"
                    @input="updateConfig"
                    placeholder="例如：30%"
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="static-data-config">
        <!-- 静态数据配置 -->
        <div class="data-input">
          <div class="input-label">X轴数据：</div>
          <textarea
            v-model="xAxisData"
            @input="handleXAxisDataInput"
            placeholder='["Mon", "Tue", "Wed", "Thu", "Fri"]'
            rows="2"
          ></textarea>
        </div>

        <!-- 系列数据配置 -->
        <div class="chart-style-config">
          <!-- 系列配置 -->
          <div class="series-config">
            <div class="series-header">
              <span>数据系列样式</span>
              <button class="add-btn" @click="addSeries">添加系列</button>
            </div>
            
            <div v-for="(series, index) in localConfig.option.series" 
                 :key="index" 
                 class="series-item">
              <div class="series-row">
                <div class="config-item">
                  <label>系列名称：</label>
                  <input 
                    type="text" 
                    v-model="series.name"
                    @input="updateConfig"
                    placeholder="系列名称"
                  >
                </div>
                <div class="config-item">
                  <label>图表类型：</label>
                  <select 
                    v-model="series.type"
                    @change="handleSeriesTypeChange(index)"
                  >
                    <option value="line">折线图</option>
                    <option value="bar">柱状图</option>
                  </select>
                </div>
                <div class="config-item">
                  <label>系列颜色：</label>
                  <el-color-picker 
                    v-model="series.itemStyle.color"
                    show-alpha
                    @change="updateConfig"
                    size="small"
                  />
                </div>
                <button 
                  v-if="localConfig.option.series.length > 1"
                  @click="removeSeries(index)" 
                  class="remove-btn"
                >删除</button>
              </div>

              <!-- 系列数据输入 -->
              <div class="series-data-input">
                <div class="config-item">
                  <label>系列数据：</label>
                  <textarea
                    v-model="seriesDataInputs[index]"
                    @input="handleSeriesDataInput($event, index)"
                    :placeholder="getSeriesPlaceholder()"
                    rows="2"
                  ></textarea>
                </div>
              </div>

              <!-- 折线图特有配置 -->
              <div v-if="series.type === 'line'" class="series-style-row">
                <div class="config-item">
                  <label>线条宽度：</label>
                  <input 
                    type="number" 
                    v-model.number="series.lineStyle.width"
                    @input="updateConfig"
                    min="1"
                    max="10"
                  >
                </div>
                <div class="config-item">
                  <label>是否平滑：</label>
                  <el-switch
                    v-model="series.smooth"
                    @change="updateConfig"
                  />
                </div>
              </div>

              <!-- 柱状图特有配置 -->
              <div v-if="series.type === 'bar'" class="series-style-row">
                <div class="config-item">
                  <label>柱条宽度：</label>
                  <input 
                    type="number" 
                    v-model.number="series.barWidth"
                    @input="updateConfig"
                    min="10"
                    max="50"
                  >
                </div>
                <div class="config-item">
                  <label>柱条间距：</label>
                  <input 
                    type="text" 
                    v-model="series.barGap"
                    @input="updateConfig"
                    placeholder="例如：30%"
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 样式配置 -->
    <div class="config-section">
      <div class="section-title">样式配置</div>
      
      <!-- 坐标轴样式 -->
      <div class="axis-style">
        <!-- X轴 -->
        <div class="config-row">
          <div class="config-item">
            <label>X轴文字：</label>
            <el-color-picker 
              v-model="localConfig.option.xAxis.axisLabel.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
          <div class="config-item">
            <label>X轴线：</label>
            <el-color-picker 
              v-model="localConfig.option.xAxis.axisLine.lineStyle.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
          <div class="config-item">
            <label>显示刻度：</label>
            <el-switch
              v-model="localConfig.option.xAxis.axisTick.show"
              @change="updateConfig"
            />
          </div>
        </div>

        <!-- Y轴 -->
        <div class="config-row">
          <div class="config-item">
            <label>Y轴文字：</label>
            <el-color-picker 
              v-model="localConfig.option.yAxis.axisLabel.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
          <div class="config-item">
            <label>Y轴线：</label>
            <el-color-picker 
              v-model="localConfig.option.yAxis.axisLine.lineStyle.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
          <div class="config-item">
            <label>分割线：</label>
            <el-color-picker 
              v-model="localConfig.option.yAxis.splitLine.lineStyle.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
        </div>
      </div>

      <!-- 图例样式 -->
      <div class="legend-style">
        <div class="config-row">
          <div class="config-item">
            <label>显示图例：</label>
            <el-switch
              v-model="localConfig.option.legend.show"
              @change="updateConfig"
            />
          </div>
          <div class="config-item">
            <label>图例位置：</label>
            <select 
              v-model="localConfig.option.legend.orient"
              @change="updateConfig"
            >
              <option value="horizontal">水平</option>
              <option value="vertical">垂直</option>
            </select>
          </div>
          <div class="config-item">
            <label>文字颜色：</label>
            <el-color-picker 
              v-model="localConfig.option.legend.textStyle.color"
              show-alpha
              @change="updateConfig"
              size="small"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CommonChartConfig',
  props: {
    config: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      localConfig: {
        width: '100%',
        height: '300px',
        backgroundColor: '#ffffff',
        option: {
          title: {
            text: '图表标题'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            show: true,
            orient: 'horizontal',
            top: '5%',
            left: 'center',
            textStyle: {
              color: '#333',
              fontSize: 12
            },
            itemWidth: 25,
            itemHeight: 14,
            itemGap: 10,
            selectedMode: 'multiple'
          },
          grid: {
            show: false,
            borderColor: '#eee',
            top: 60,
            right: 20,
            bottom: 40,
            left: 50,
            containLabel: true
          },
          xAxis: {
            show: true,
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            name: '',
            axisLabel: {
              show: true,
              color: '#333',
              fontSize: 12
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#333'
              }
            },
            axisTick: {
              show: true
            }
          },
          yAxis: {
            show: true,
            type: 'value',
            name: '',
            axisLabel: {
              show: true,
              color: '#333',
              fontSize: 12
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#333'
              }
            },
            axisTick: {
              show: true
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#eee'
              }
            }
          },
          series: [{
            name: '数据系列1',
            type: 'line',
            data: [150, 230, 224, 218, 135, 147, 260],
            itemStyle: {
              color: '#5470c6'
            },
            lineStyle: {
              width: 2
            }
          }]
        }
      },
      chartType: 'line',
      xAxisData: '["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]',
      seriesDataInputs: ['[150, 230, 224, 218, 135, 147, 260]'],
      dataSourceType: 'static',
      apiConfig: {
        url: '',
        method: 'GET',
        autoRefresh: false,
        refreshInterval: 10,
        mapping: {
          categories: 'data.categories',
          series: 'data.series'
        }
      },
      refreshTimer: null,
      defaultChartType: 'line',
      lineStyle: {
        width: 2,
        smooth: false
      },
      barStyle: {
        width: 30,
        gap: '30%'
      }
    }
  },
  created() {
    // 确保配中包含所有必要的属性
    const mergedConfig = {
      ...this.localConfig,
      ...this.config
    };
    
    // 确保 option 存在
    if (!mergedConfig.option) {
      mergedConfig.option = this.localConfig.option;
    }

    // 确保 legend 配置完整
    mergedConfig.option.legend = {
      show: true,
      orient: 'horizontal',
      top: '5%',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      itemWidth: 25,
      itemHeight: 14,
      itemGap: 10,
      selectedMode: 'multiple',
      ...(mergedConfig.option.legend || {})
    };

    // 确保 legend.textStyle 存在
    if (!mergedConfig.option.legend.textStyle) {
      mergedConfig.option.legend.textStyle = {
        color: '#333',
        fontSize: 12
      };
    }

    // 确保其他配置完整
    // ... 其他配置保持不变

    this.localConfig = mergedConfig;
    this.chartType = this.localConfig.option.series[0].type;
    this.xAxisData = JSON.stringify(this.localConfig.option.xAxis.data);
    this.seriesDataInputs = this.localConfig.option.series.map(series => 
      JSON.stringify(series.data)
    );

    // 如有初始的 API 配置，则使用它
    if (this.config.dataSourceType === 'api' && this.config.apiConfig) {
      this.dataSourceType = 'api';
      this.apiConfig = {
        ...this.apiConfig,
        ...this.config.apiConfig
      };
    }

    // 如果初始配置是 API 类型，启动定时刷新
    if (this.dataSourceType === 'api' && this.apiConfig.autoRefresh) {
      this.resetRefreshTimer();
    }
  },
  methods: {
    updateConfig() {
      // 确保配置中包含数据源类型和 API 配置
      const updatedConfig = {
        ...this.localConfig,
        dataSourceType: this.dataSourceType,
        apiConfig: this.dataSourceType === 'api' ? { ...this.apiConfig } : undefined
      };
      
      this.$emit('update:config', updatedConfig);
    },
    handleChartTypeChange() {
      if (this.chartType === 'pie') {
        // 转换为饼图数据格式
        const xAxisData = JSON.parse(this.xAxisData);
        const seriesData = JSON.parse(this.seriesDataInputs[0]);
        
        // 创建饼图配置
        const pieData = seriesData.map((value, index) => ({
          name: xAxisData[index] || `数据${index + 1}`,
          value,
          itemStyle: {
            color: this.getRandomColor()
          }
        }));

        this.localConfig.option = {
          title: this.localConfig.option.title,
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            show: true,
            orient: 'horizontal',
            top: '5%',
            left: 'center',
            textStyle: {
              color: '#333',
              fontSize: 12
            },
            itemWidth: 25,
            itemHeight: 14,
            itemGap: 10,
            selectedMode: 'multiple'
          },
          series: [{
            name: '数据系列',
            type: 'pie',
            radius: '50%',
            roseType: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {d}%'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: pieData
          }]
        };
      } else {
        // 从饼图切换回其他图表类型
        if (!this.localConfig.option.xAxis) {
          // 恢复坐标轴配置
          this.localConfig.option.xAxis = {
            type: 'category',
            data: JSON.parse(this.xAxisData),
            name: ''
          };
          this.localConfig.option.yAxis = {
            type: 'value',
            name: ''
          };
          
          // 转换数据格式
          const pieData = this.localConfig.option.series[0].data;
          this.localConfig.option.series = [{
            name: this.localConfig.option.series[0].name,
            type: this.chartType,
            data: pieData.map(item => item.value),
            itemStyle: {
              color: this.getRandomColor()
            },
            ...(this.chartType === 'line' ? {
              lineStyle: { width: 2 }
            } : {
              barWidth: 30
            })
          }];
          
          this.localConfig.option.tooltip = {
            trigger: 'axis'
          };
        } else {
          // 在非饼图类型之间切换
          this.localConfig.option.series = this.localConfig.option.series.map(series => ({
            ...series,
            type: this.chartType,
            // 确保每个系列都有完整的配置
            itemStyle: {
              ...series.itemStyle,
              color: series.itemStyle?.color || this.getRandomColor()
            },
            ...(this.chartType === 'line' ? {
              lineStyle: { 
                width: series.lineStyle?.width || 2,
                type: 'solid'
              },
              symbol: 'circle',
              symbolSize: 6,
              showSymbol: true,
              smooth: false
            } : {
              barWidth: series.barWidth || 30,
              barGap: '30%'
            })
          }));
        }
      }
      
      // 确保图例配置完整
      this.localConfig.option.legend = {
        ...this.localConfig.option.legend,
        type: 'plain',
        selectedMode: this.localConfig.option.legend.selectedMode || 'multiple',
        selected: this.localConfig.option.series.reduce((acc, series) => {
          acc[series.name] = true;
          return acc;
        }, {})
      };
      
      this.updateConfig();
    },
    handleXAxisDataInput() {
      try {
        const data = JSON.parse(this.xAxisData)
        if (Array.isArray(data)) {
          this.localConfig.option.xAxis.data = data
          this.updateConfig()
        }
      } catch (e) {
        console.error('X轴数据格式错误:', e)
      }
    },
    handleSeriesDataInput(event, index) {
      try {
        const data = JSON.parse(this.seriesDataInputs[index]);
        if (Array.isArray(data)) {
          this.localConfig.option.series[index].data = data;
          this.updateConfig();
        }
      } catch (e) {
        console.error('系列数据格式错误:', e);
      }
    },
    addSeries() {
      const newSeries = {
        name: `数据系列${this.localConfig.option.series.length + 1}`,
        type: 'line', // 默认类型
        data: Array(this.localConfig.option.xAxis.data.length).fill(0),
        itemStyle: {
          color: this.getRandomColor()
        },
        lineStyle: {
          width: 2,
          type: 'solid'
        },
        smooth: false,
        barWidth: 30,
        barGap: '30%'
      };
      
      this.localConfig.option.series.push(newSeries);
      this.seriesDataInputs.push('[' + newSeries.data.join(',') + ']');
      this.updateConfig();
    },
    
    removeSeries(index) {
      this.localConfig.option.series.splice(index, 1);
      this.seriesDataInputs.splice(index, 1);
      this.updateConfig();
    },
    
    getRandomColor() {
      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666',
        '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
      ];
      return colors[this.localConfig.option.series.length % colors.length];
    },
    getSeriesPlaceholder() {
      if (this.chartType === 'pie') {
        return '请输入数据值，格式如：[150, 230, 224, 218, 135, 147, 260]'
      }
      return '请输入数据，格式如：[150, 230, 224, 218, 135, 147, 260]'
    },
    addPieDataItem() {
      const newItem = {
        name: `数据项${this.localConfig.option.series[0].data.length + 1}`,
        value: 0,
        itemStyle: {
          color: this.getRandomColor()
        }
      };
      this.localConfig.option.series[0].data.push(newItem);
      this.updateConfig();
    },

    removePieDataItem(index) {
      this.localConfig.option.series[0].data.splice(index, 1);
      this.updateConfig();
    },

    handleLegendSelectChange(value) {
      // 确保所有系列的配置完整性
      this.localConfig.option.series = this.localConfig.option.series.map(series => ({
        ...series,
        type: series.type || this.chartType,
        itemStyle: {
          ...series.itemStyle,
          color: series.itemStyle?.color || this.getRandomColor()
        },
        ...(series.type === 'line' ? {
          lineStyle: { 
            width: series.lineStyle?.width || 2,
            type: 'solid'
          },
          symbol: 'circle',
          symbolSize: 6,
          showSymbol: true,
          smooth: false
        } : {
          barWidth: series.barWidth || 30,
          barGap: '30%'
        })
      }));
      
      this.updateConfig();
    },
    handleDataSourceChange() {
      // 更新数据源类型
      this.localConfig.dataSourceType = this.dataSourceType;
      
      if (this.dataSourceType === 'api') {
        // 确保 apiConfig 存在
        this.localConfig.apiConfig = {
          ...this.apiConfig
        };
        
        // 切换到远程数据时，尝试立即获取数据
        if (this.apiConfig.url) {
          this.fetchApiData();
        }
      } else {
        // 切换到静态数据时，清除定时器
        this.clearRefreshTimer();
      }
      
      // 更新配置
      this.updateConfig();
    },
    handleApiConfigChange() {
      // 更新 API 配置
      this.localConfig.apiConfig = {
        ...this.apiConfig
      };
      
      // 配变更时重置定时器
      this.resetRefreshTimer();
      
      // 更新配置
      this.updateConfig();
    },
    async fetchApiData() {
      try {
        const response = await fetch(this.apiConfig.url, {
          method: this.apiConfig.method,
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 获取数据
        const categories = this.getValueByPath(data, this.apiConfig.mapping.categories) || [];
        const series = this.getValueByPath(data, this.apiConfig.mapping.series) || [];
        
        // 更新图表数据，保持每个系列的样式配置
        this.localConfig.option.xAxis.data = categories;
        this.xAxisData = JSON.stringify(categories);
        
        // 更新系列数据时保持每个系列的样式配置
        this.localConfig.option.series = series.map((item, index) => {
          const existingSeries = this.localConfig.option.series[index] || {};
          return {
            name: item.name,
            type: existingSeries.type || 'line',
            data: item.data,
            itemStyle: {
              color: existingSeries.itemStyle?.color || this.getRandomColor()
            },
            // 保持现有的样式配置
            lineStyle: existingSeries.type === 'line' ? existingSeries.lineStyle : { width: 2, type: 'solid' },
            smooth: existingSeries.type === 'line' ? existingSeries.smooth : false,
            barWidth: existingSeries.type === 'bar' ? existingSeries.barWidth : 30,
            barGap: existingSeries.type === 'bar' ? existingSeries.barGap : '30%'
          };
        });
        
        this.seriesDataInputs = series.map(item => JSON.stringify(item.data));
        this.updateConfig();
      } catch (error) {
        console.error('获取远程数据失败:', error);
        alert('获取远程数据失败: ' + error.message);
      }
    },

    resetRefreshTimer() {
      this.clearRefreshTimer();
      if (this.dataSourceType === 'api' && 
          this.apiConfig.autoRefresh && 
          this.apiConfig.url && 
          this.apiConfig.refreshInterval > 0) {
        this.refreshTimer = setInterval(() => {
          this.fetchApiData();
        }, this.apiConfig.refreshInterval * 1000);
      }
    },

    clearRefreshTimer() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },

    async testApi() {
      try {
        await this.fetchApiData();
        alert('接口测试成功！');
      } catch (error) {
        alert('接口测试失败：' + error.message);
      }
    },

    // 根据路径获取对象值的辅助方法
    getValueByPath(obj, path) {
      return path.split('.').reduce((acc, part) => {
        return acc && acc[part];
      }, obj);
    },
    handleDefaultChartTypeChange() {
      // 更新默认图表类型
      this.updateSeriesStyle();
    },
    handleLineStyleChange() {
      if (this.defaultChartType === 'line') {
        this.updateSeriesStyle();
      }
    },
    handleBarStyleChange() {
      if (this.defaultChartType === 'bar') {
        this.updateSeriesStyle();
      }
    },
    updateSeriesStyle() {
      // 更新所有系列的样式
      this.localConfig.option.series = this.localConfig.option.series.map(series => ({
        ...series,
        type: this.defaultChartType,
        ...(this.defaultChartType === 'line' ? {
          lineStyle: {
            width: this.lineStyle.width,
            type: 'solid'
          },
          smooth: this.lineStyle.smooth
        } : {
          barWidth: this.barStyle.width,
          barGap: this.barStyle.gap
        })
      }));
      
      this.updateConfig();
    },
    handleSeriesTypeChange(index) {
      const series = this.localConfig.option.series[index];
      
      // 确保系列具有所有必要的样式属性
      if (series.type === 'line') {
        series.lineStyle = series.lineStyle || {
          width: 2,
          type: 'solid'
        };
        series.smooth = series.smooth || false;
      } else if (series.type === 'bar') {
        series.barWidth = series.barWidth || 30;
        series.barGap = series.barGap || '30%';
      }
      
      this.updateConfig();
    }
  },
  computed: {
    canAddSeries() {
      return this.chartType !== 'pie';
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.clearRefreshTimer();
  }
}
</script>

<style scoped>
/* 整体容器样式 */
.config-group {
  margin-bottom: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.config-group h4 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #1a1a1a;
  font-weight: 600;
}

/* 配置区块样式 */
.config-section {
  margin-bottom: 24px;
  padding: 20px;
  background: transparent;
  border-radius: 8px;
  box-shadow: none;
}

.config-section:last-child {
  margin-bottom: 0;
}

/* 区块标题样式 */
.section-title {
  font-size: 14px;
  color: #262626;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
}

/* 配置行样式 */
.config-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.config-row:last-child {
  margin-bottom: 0;
}

/* 配置项样式 */
.config-item.flex-item {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 260px;
  flex: 0 1 calc(50% - 8px);
}

.config-item.flex-item label {
  width: auto;
  min-width: 90px;
  white-space: nowrap;
  color: #595959;
  font-size: 13px;
}

/* 输入框和选择器样式 */
.config-item.flex-item input,
.config-item.flex-item select {
  flex: 1;
  min-width: 120px;
  padding: 6px 12px;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 13px;
  color: #262626;
  background: #fff;
  transition: all 0.3s;
}

.config-item.flex-item input:hover,
.config-item.flex-item select:hover {
  border-color: #40a9ff;
}

.config-item.flex-item input:focus,
.config-item.flex-item select:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

/* 数据编辑器样式 */
.data-editor {
  margin-top: 16px;
  background: #fafafa;
  padding: 20px;
  border-radius: 8px;
  width: 100%;
}

.editor-title {
  font-size: 13px;
  color: #595959;
  margin-bottom: 12px;
  font-weight: 500;
}

textarea {
  width: 100%;
  box-sizing: border-box;
}

/* 系列配置样式 */
.series-config {
  margin-top: 20px;
}

.series-header {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.series-title {
  font-size: 14px;
  color: #262626;
  font-weight: 500;
}

.add-series-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;
}

.add-series-btn:hover {
  background: #40a9ff;
}

/* 系列项样式 */
.series-item {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
  width: 100%;
}

.series-item-header {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.series-info,
.series-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.series-index {
  font-size: 13px;
  color: #8c8c8c;
  font-weight: 500;
}

.series-name-input {
  width: 160px;
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 13px;
}

.series-type-select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 13px;
}

.remove-series-btn {
  padding: 6px 16px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.3s;
}

.remove-series-btn:hover {
  background: #ff7875;
}

/* 数据映射样式 */
.mapping-example {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.example-title {
  font-size: 13px;
  color: #595959;
  margin-bottom: 12px;
  font-weight: 500;
}

.example-code {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #262626;
  border: 1px solid #f0f0f0;
}

/* API 操作按钮样式 */
.api-actions {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.test-api-btn {
  padding: 8px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.test-api-btn:hover {
  background: #40a9ff;
}

.api-reference {
  margin-top: 10px;
  color: #409EFF;
  font-size: 13px;
}

.api-reference a {
  color: #409EFF;
  text-decoration: none;
}

.api-reference a:hover {
  text-decoration: underline;
}

.mapping-example {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
}

.example-code {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #333;
  border: 1px solid #eee;
  margin: 0;
  white-space: pre-wrap;
}

/* 开关样式优化 */
:deep(.el-switch) {
  margin-right: 8px;
}

/* 颜色选择器样式优化 */
:deep(.el-color-picker) {
  margin-right: 8px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 当容器宽度小于600px时，配置项占满整行 */
@media screen and (max-width: 600px) {
  .config-item.flex-item {
    flex: 0 1 100%;
  }
}
</style> 